<template>
  <div class="picture-manage-container">
    <div class="content-wrapper">
      <!-- 标题和操作按钮在同一行 -->
      <div class="header-section">
        <h2 class="page-title">图片管理</h2>
        <div class="action-buttons">
          <a-button type="primary" @click="handleCreateImage">
            <template #icon>
              <icon-plus/>
            </template>
            创建图片
          </a-button>
          <a-button @click="handleBatchCreateImage">
            <template #icon>
              <icon-plus/>
            </template>
            批量导入图片
          </a-button>
        </div>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="search-section">
        <div class="search-row">
          <div class="search-inputs">
            <div class="search-item">
              <span class="search-label">关键词:</span>
              <a-input v-model="searchForm.keyword" placeholder="从名称和简介搜索"/>
            </div>
            <div class="search-item">
              <span class="search-label">类型:</span>
              <a-select v-model="searchForm.category" placeholder="请输入类型">
                <a-option :value="category" v-for="category in categories">{{ category }}</a-option>
              </a-select>
            </div>
            <div class="search-item">
              <span class="search-label">标签:</span>
              <a-input v-model="searchForm.tags" placeholder="请输入标签"/>
            </div>
            <div class="search-item">
              <span class="search-label">审核状态:</span>
              <a-select v-model="searchForm.reviewStatus" placeholder="请输入审核状态" allow-clear>
                <a-option value="1">通过</a-option>
                <a-option value="2">拒绝</a-option>
                <a-option value="0">待审核</a-option>
              </a-select>
            </div>
          </div>
          <div class="search-buttons">
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button class="refresh-btn" @click="handleReset">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </div>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <a-table
            row-key="id"
            :columns="columns"
            :data="tableData"
            :pagination="pagination"
            @page-change="onPageChange"
        >
          <!-- ID列 -->
          <template #id="{ record }">
            <div>{{ record.id }}</div>
          </template>

          <!-- 图片列 -->
          <template #image="{ record }">
            <div class="image-preview">
              <img :src="record.thumbnailUrl??record.url" :alt="record.picName"/>
            </div>
          </template>

          <!-- 图片名称列 -->
          <template #name="{ record }">
            <span>{{ record.picName }}</span>
          </template>

          <!-- 简介列 -->
          <template #description="{ record }">
            <span>{{ record.introduction }}</span>
          </template>

          <!-- 类型列 -->
          <template #type="{ record }">
            <span>{{ record.category }}</span>
          </template>

          <!-- 标签列 - 修改为竖直排列 -->
          <template #tags="{ record }">
            <div class="tags-container">
              <a-tag
                  v-for="tag in record.tags"
                  :key="tag"
                  color="blue"
                  class="tag-item"
              >
                {{ tag }}
              </a-tag>
            </div>
          </template>

          <!-- 图片信息列 -->
          <template #imageInfo="{ record }">
            <div class="image-info">
              <div>宽度: {{ record.picWidth }}</div>
              <div>高度: {{ record.picHeight }}</div>
              <div>宽高比: {{ record.picScale }}</div>
              <div>大小: {{ formatSize(record.picSize) }}</div>
            </div>
          </template>

          <!-- 审核信息列 -->
          <template #auditInfo="{ record }">
            <div class="image-info">
              <!--              <div>审核状态: {{ record.reviewStatus === 0 ? '待审核' : record.reviewStatus === 1 ? '通过' : '拒绝' }}</div>-->
              <a-space v-if="record.reviewStatus === 0">
                <a-badge status="processing"/>
                待审核
              </a-space>
              <a-space v-else-if="record.reviewStatus === 1">
                <a-badge status="success"/>
                通过
              </a-space>
              <a-space v-else>
                <a-badge status="danger"/>
                拒绝
              </a-space>
            </div>
          </template>

          <!-- 创建时间列 -->
          <template #createTime="{ record }">
            <div>{{ formatTime(record.createTime, "YYYY-MM-DD") }}</div>
          </template>
          <!-- 操作列 -->
          <template #operations="{ record }">
            <div class="operations-vertical">
              <a-button type="text" class="operation-link" @click="handleEdit(record)">查看</a-button>
              <a-button type="text" class="operation-link" status="danger" @click="handleDelete(record)">删除</a-button>
            </div>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 图片详情抽屉 -->
    <a-drawer
        :visible="drawerVisible"
        @cancel="closeDrawer"
        @ok="closeDrawer"
        :width="600"
        :footer="false"
        unmountOnClose
    >
      <template #title>
        图片详情 - {{ currentImage?.picName }}
      </template>
      <div v-if="currentImage" class="drawer-content">
        <!-- 图片和基本信息放在同一行 -->
        <div class="drawer-header">
          <div class="drawer-image-container">
            <img :src="currentImage.url" :alt="currentImage.picName" class="drawer-image"/>
          </div>

          <div class="drawer-basic-info">
            <a-descriptions :data="imageDescriptionData" title="基本信息" bordered layout="horizontal" :column="1"
                            size="small"/>
          </div>
        </div>

        <a-typography>
          <a-typography-title :heading="5">图片简介</a-typography-title>
          <a-typography-text>{{ currentImage.introduction }}</a-typography-text>
        </a-typography>

        <a-divider/>
        <!-- 图片元信息和审核信息放在同一行 -->
        <div class="drawer-info-row">
          <div class="drawer-meta-info">
            <a-descriptions :data="imageMetaData" title="图片元信息" bordered layout="horizontal" :column="1"
                            size="small"/>
          </div>

          <div class="drawer-audit-info">
            <a-descriptions :data="auditData" title="审核信息" bordered layout="horizontal" :column="1" size="small"/>
          </div>
        </div>
      </div>
      <a-divider/>
      <div class="review" v-if="currentImage.reviewStatus!==1">
        <div>
          <a-typography-title :heading="5">审核意见</a-typography-title>
        </div>
        <a-space>
          <a-input :style="{width:'200px'}" v-model="reviewMessage" placeholder="请输入审核意见" allow-clear/>
          <a-button type="primary" @click="reviewPicture(currentImage.id,1)">通过</a-button>
          <a-button @click="reviewPicture(currentImage.id,2)">拒绝</a-button>
        </a-space>


      </div>
    </a-drawer>

    <!-- 批量创建图片模态框 -->
    <a-modal
      :visible="batchCreateVisible"
      @update:visible="(val) => batchCreateVisible = val"
      title="批量创建图片"
      @cancel="resetBatchCreateForm"
      @before-ok="submitBatchCreate"
      :width="500"
    >
      <a-form :model="batchCreateForm" layout="vertical">
        <a-form-item field="category" label="图片类别" required>
          <a-select v-model="batchCreateForm.category" placeholder="请选择图片类别">
            <a-option v-for="category in categories" :key="category" :value="category">
              {{ category }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="prefix" label="图片前缀" required>
          <a-input v-model="batchCreateForm.prefix" placeholder="请输入图片前缀" />
        </a-form-item>

        <a-form-item field="tags" label="图片标签" required>
          <a-select
            v-model="batchCreateForm.selectedTags"
            multiple
            placeholder="请选择标签（最多4个）"
            allow-clear
            :max-tag-count="4"
            :limit="4"
          >
            <a-option v-for="tag in tags" :key="tag" :value="tag">
              {{ tag }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="source" label="来源站点" required>
          <a-select v-model="batchCreateForm.source" placeholder="请选择来源站点">
            <a-option value="1">Pexels</a-option>
            <a-option value="2">Unsplash</a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="count" label="导入数量" required>
          <a-select v-model="batchCreateForm.count" placeholder="请选择导入数量">
            <a-option value="5">5张</a-option>
            <a-option value="10">10张</a-option>
            <a-option value="20">20张</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, computed} from 'vue';
import {Message, Modal} from '@arco-design/web-vue';
import {IconPlus, IconRefresh} from '@arco-design/web-vue/es/icon';
import {formatSize, formatTime} from "../../utils";
import type {PicturePageQueryRequest, PictureViewVo,PictureReviewRequest,PictureUploadByBatchRequest} from "../../service/typing";
import {
  deletePictureRequestByPost,
  pageQueryPictureRequestByPost,
  reviewPictureRequestByPost, uploadPictureByBatchByPost
} from "../../service/pictureRequest";

// 抽屉相关状态
const drawerVisible = ref(false);
const currentImage = ref<PictureViewVo | null>(null);

// 抽屉数据
const imageDescriptionData = computed(() => {
  if (!currentImage.value) return [];

  return [
    {
      label: 'ID',
      value: currentImage.value.id
    },
    {
      label: '格式',
      value: currentImage.value.picFormat
    },
    {
      label: '类型',
      value: currentImage.value.category
    },
    {
      label: '创建时间',
      value: formatTime(currentImage.value.createTime, 'YYYY-MM-DD HH:mm:ss')
    },
    {
      label: '更新时间',
      value: formatTime(currentImage.value.updateTime, 'YYYY-MM-DD HH:mm:ss')
    }
  ];
});

const imageMetaData = computed(() => {
  if (!currentImage.value) return [];

  return [
    {
      label: '格式',
      value: currentImage.value.picFormat
    },
    {
      label: '宽度',
      value: `${currentImage.value.picWidth}px`
    },
    {
      label: '高度',
      value: `${currentImage.value.picHeight}px`
    },
    {
      label: '宽高比',
      value: currentImage.value.picScale
    },
    {
      label: '文件大小',
      value: `${formatSize(currentImage.value.picSize)}`
    },
  ];
});

const auditData = computed(() => {
  if (!currentImage.value) return [];

  return [
    {
      label: '审核状态',
      value: currentImage.value.reviewStatus === 0 ? '待审核' : currentImage.value.reviewStatus === 1 ? '通过' : '拒绝'
    },
    {
      label: '审核信息',
      value: currentImage.value.reviewMessage || '无'
    },
    {
      label: '审核人ID',
      value: currentImage.value.reviewerId || '无'
    },
    {
      label: '审核时间',
      value: currentImage.value.reviewTime ? formatTime(currentImage.value.reviewTime, "YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: '上传用户ID',
      value: currentImage.value.userId
    },
  ];
});

const reviewMessage = ref<string>('审核通过')

// 定义表格列接口
interface TableColumn {
  title: string;
  dataIndex?: string;
  slotName?: string;
  width: number;
  fixed?: string;
}

// 表单数据
const categories = ['', '自然风光', '城市建筑', '人物肖像', '动物世界', '美食佳肴', '旅行探险', '科技数码', '艺术设计', '体育运动']
const tags = ['风景', '人像', '建筑', '旅行', '美食', '动物', '植物', '城市', '黑白', '夜景', '山水', '海洋', '街头', '创意', '复古']
const searchForm = reactive({
  keyword: '',
  category: '',
  tags: '',
  reviewStatus: ''
});

// 表格列定义
const columns: TableColumn[] = [
  {
    title: 'id',
    dataIndex: 'id',
    slotName: 'id',
    width: 170,
  },
  {
    title: '图片',
    slotName: 'image',
    width: 120,
  },
  {
    title: '名称',
    dataIndex: 'picName',
    slotName: 'name',
    width: 150,
  },
  {
    title: '类型',
    dataIndex: 'category',
    slotName: 'type',
    width: 100,
  },
  {
    title: '标签',
    slotName: 'tags',
    width: 100,
  },
  {
    title: '图片信息',
    slotName: 'imageInfo',
    width: 150,
  },
  {
    title: '审核信息',
    slotName: 'auditInfo',
    width: 90,
  },
  {
    title: '创建时间',
    slotName: 'createTime',
    width: 120,
  },
  {
    title: '操作',
    slotName: 'operations',
    width: 100,
  }
];

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showPageSize: true,
});

// 表格数据
const tableData = ref<PictureViewVo[]>([]);

// 获取图片列表数据
const fetchImageList = async () => {
  try {
    const picturePageQueryRequest = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      sortField: 'create_time',
      sort: "descend",
      searchText: searchForm.keyword,
      category: searchForm.category,
      reviewStatus: parseInt(searchForm.reviewStatus)
    } as PicturePageQueryRequest
    const res = await pageQueryPictureRequestByPost(picturePageQueryRequest)
    if (res.code != 200) {
      Message.error("获取图片列表失败")
    }
    // 模拟数据
    tableData.value = res.data.data;

    // 设置总数
    pagination.total = res.data.total;
  } catch (error) {
    console.error('获取图片列表失败:', error);
    Message.error('获取图片列表失败');
  }
};

// 页码变化
const onPageChange = (page: number) => {
  pagination.current = page;
  fetchImageList();
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  fetchImageList();
};

// 创建图片
const handleCreateImage = () => {
  // 跳转到创建图片页面或打开创建图片模态框
  Message.info('跳转到创建图片页面');
};

// 批量创建图片模态框相关状态
const batchCreateVisible = ref(false);
const batchCreateForm = reactive({
  category: '',
  prefix: '',
  selectedTags: [] as string[],
  source: '1',
  count: '5'
});

// 批量创建图片
const handleBatchCreateImage = () => {
  batchCreateVisible.value = true;
};

// 提交批量创建
const submitBatchCreate = async () => {
  try {
    // 验证表单
    if (!batchCreateForm.category) {
      Message.error('请选择图片类别');
      return;
    }
    if (!batchCreateForm.prefix) {
      Message.error('请输入图片前缀');
      return;
    }
    if (batchCreateForm.selectedTags.length === 0) {
      Message.error('请至少选择一个标签');
      return;
    }

    // 构建请求参数
    const pictureUploadByBatchRequest = {
      category: batchCreateForm.category,
      namePrefix: batchCreateForm.prefix,
      tags: batchCreateForm.selectedTags,
      source: parseInt(batchCreateForm.source),
      count: parseInt(batchCreateForm.count)
    } as PictureUploadByBatchRequest

    const res = await uploadPictureByBatchByPost(pictureUploadByBatchRequest)
    if (res.code!=200){
      Message.error('批量创建图片失败');
      return
    }
    Message.success('批量创建图片成功');
    batchCreateVisible.value = false;
    fetchImageList();
  } catch (error) {
    console.error('批量创建图片失败:', error);
    Message.error('批量创建图片失败');
  }
};

// 重置批量创建表单
const resetBatchCreateForm = () => {
  batchCreateForm.category = '';
  batchCreateForm.prefix = '';
  batchCreateForm.selectedTags = [];
  batchCreateForm.source = '1';
  batchCreateForm.count = '5';
};

// 编辑图片 - 修改为打开抽屉
const handleEdit = (record: PictureViewVo) => {
  // 设置当前选中的图片
  currentImage.value = record;
  // 打开抽屉
  drawerVisible.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
  // 延迟清空当前图片，避免闪烁
  setTimeout(() => {
    currentImage.value = null;
  }, 300);
};

// 删除图片
const handleDelete = (record: PictureViewVo) => {
  Modal.warning({
    title: '确认删除',
    content: `确定要删除图片 "${record.picName}" 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      // 调用删除API
      const res = await deletePictureRequestByPost(record.id)
      if (res.code!=200){
        Message.error(`图片 ${record.id} 删除失败`);
        return
      }
      Message.success(`图片 ${record.id} 删除成功`);
      fetchImageList()
    },
  });
};

// 添加重置方法
const handleReset = () => {
  searchForm.keyword = '';
  searchForm.category = '';
  searchForm.tags = '';
  searchForm.reviewStatus = '';
  fetchImageList();
};

const reviewPicture = async (id: number, reviewStatus: number) => {

  if (id < 1 || id == null) {
    return
  }

  let message = reviewMessage.value
  if (reviewStatus === 2 && reviewMessage.value === "审核通过") {
    message = "审核不通过"
  }

  const pictureReviewRequest = {
    id: id,
    reviewStatus: reviewStatus,
    reviewMessage: message,
  } as PictureReviewRequest


  const res = await reviewPictureRequestByPost(pictureReviewRequest)

  if (res.code != 200 || !res.data) {
    Message.error("提交审核失败:" + res.description)
  }

  Message.success("审核成功")
  reviewMessage.value = "审核通过"
  closeDrawer()
  fetchImageList();

}

onMounted(() => {
  // 组件挂载时获取图片列表
  fetchImageList();
});
</script>

<style scoped>
.picture-manage-container {
  padding: 16px;
  background-color: #ffffff;
  min-height: 100vh;
}

.content-wrapper {
  width: 100%;
  position: relative;
}

.header-section, .search-section {
  position: relative;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
  color: #1d2129;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
  width: 100%;
  position: relative;
}

.search-inputs {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 8px;
  max-width: calc(100% - 190px);
  overflow-x: auto;
}

.search-buttons {
  position: absolute;
  right: 0;
  display: flex;
  gap: 8px;
}

.search-item {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.search-label {
  margin-right: 8px;
  white-space: nowrap;
  color: #1d2129;
  font-size: 14px;
}

.search-item :deep(.arco-input),
.search-item :deep(.arco-select) {
  width: 180px;
}

.table-section {
  background: #fff;
  padding: 0;
  overflow: hidden;
}

.image-preview {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-info {
  font-size: 12px;
  line-height: 1.6;
}

.operations-vertical {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.operation-link {
  color: #165DFF;
  padding: 0;
  height: auto;
  font-size: 14px;
}

/* 状态单元格 */
.status-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-online {
  background-color: #00b42a;
}

.status-offline {
  background-color: #86909c;
}

/* 标签容器样式 - 垂直排列 */
.tags-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.tag-item {
  margin: 0;
}

:deep(.arco-table-th) {
  background-color: #ffffff;
  color: #1d2129;
  font-weight: 500;
  border-bottom: 1px solid #e5e6eb;
}

:deep(.arco-table-td) {
  border-bottom: 1px solid #e5e6eb;
}

:deep(.arco-pagination) {
  margin-top: 16px;
  justify-content: center;
  padding-top: 16px;
}

/* 禁用表格的滚动条 */
:deep(.arco-table-body) {
  overflow: visible;
}

:deep(.arco-table-header) {
  overflow: visible;
}

:deep(.arco-scrollbar) {
  height: auto !important;
}

:deep(.arco-scrollbar__bar) {
  display: none !important;
}

:deep(.arco-table-container) {
  height: auto !important;
}

/* 表格行悬停效果 */
:deep(.arco-table-tr:hover) {
  background-color: #f7f8fa !important;
}

/* 去掉表格边框和阴影 */
:deep(.arco-table) {
  border: none;
  box-shadow: none;
}

/* 抽屉样式 */
.drawer-content {
  padding: 16px 0;
}

/* 抽屉头部布局 - 图片和基本信息并排 */
.drawer-header {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.drawer-image-container {
  flex: 0 0 250px;
}

.drawer-basic-info {
  flex: 1;
}

.drawer-image {
  width: 100%;
  max-height: 250px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.drawer-section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #1d2129;
}

.drawer-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

:deep(.arco-descriptions-title) {
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
}

:deep(.arco-descriptions-item-label) {
  font-weight: 500;
  color: #4e5969;
}

:deep(.arco-descriptions-item-value) {
  color: #1d2129;
}

/* 图片元信息和审核信息并排 */
.drawer-info-row {
  display: flex;
  font-size: 12px;
  gap: 20px;
}

.drawer-meta-info {
  flex: 0 0 210px;
}

.drawer-audit-info {
  flex: 1;
}

.selected-tags {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>